`include "macro.v"
module IO_bridge (
    input wire clk,
    input wire rst_n,
    input wire [31:0] addr,
    input wire [31:0] wdata,
    input wire wen,
    output reg [31:0] rdata,
    
    // dram
    input wire [1:0] sd_sel,
    input wire [2:0] ld_sel,
    // others
    input wire [23:0] device_switch,
    output reg [23:0] device_led,
    // digital
    output wire [7:0] led_en,
	output wire led_ca,
	output wire led_cb,
    output wire led_cc,
	output wire led_cd,
	output wire led_ce,
	output wire led_cf,
	output wire led_cg,
	output wire led_dp
);

reg [31:0] device_digital;
wire [31:0] dram_rd;

reg led_we;
reg dram_we;
reg digital_we;
always @(*) begin
    if(addr == 32'hFFFFF000 && wen) begin
        // digital
        led_we = 1'b0;
        dram_we = 1'b0;
        digital_we = 1'b1;
    end else if(addr == 32'hFFFFF060 && wen) begin
        // led
        led_we = 1'b1;
        dram_we = 1'b0;
        digital_we = 1'b0;
    end else if(wen) begin
        // dram
        led_we = 1'b0;
        dram_we = 1'b1;
        digital_we = 1'b0;
    end else begin
        led_we = 1'b0;
        dram_we = 1'b0;
        digital_we = 1'b0;
    end
end


// rdata
always @(*) begin
    // switch
    if (addr == 32'hFFFFF070) begin
        rdata = {8'b0, device_switch};
    end else begin
        rdata = dram_rd;
    end
end

// device_led
always @(*) begin
    device_led = device_switch;
    // if (led_we) begin
    //     device_led = wdata[23:0];
    // end else begin
    //     device_led = device_led;
    // end
end

// device_digital
always @(*) begin
    // device_digital = {8'b0, device_led};
    if (digital_we) begin
        device_digital = wdata;
    end else begin
        device_digital = device_digital;
    end
end

wire [31:0] dram_addr;
assign dram_addr = addr;// - 'h4000;
wire dram_clk = ~clk;
DRAM u_dram(
    .clk(dram_clk),
    .dram_we(dram_we),
    .sd_sel(sd_sel),
    .ld_sel(ld_sel),
    .addr(dram_addr),
    .wdin(wdata),
    .rd(dram_rd)
);

led_display_ctrl u_led_ctrl(
    .clk(clk),
    .rst_n(rst_n),
    // .wen(digital_we),
    .data_in(device_digital),
    .led_en(led_en),
    .led_ca(led_ca),
    .led_cb(led_cb),
    .led_cc(led_cc),
    .led_cd(led_cd),
    .led_ce(led_ce),
    .led_cf(led_cf),
    .led_cg(led_cg),
    .led_dp(led_dp)
);

endmodule